// import { IParamsResult } from '@/shared/core/decorator/ListParams.decorator'
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { CreateArticleDto } from './dto/create-article.dto'
import { UpdateArticleDto } from './dto/update-article.dto'
import { ArticleEntity } from './entities/article.entity'

@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(ArticleEntity)
    private readonly articleRepository: Repository<ArticleEntity>,
  ) {}

  // 新增
  async create(dto: CreateArticleDto) {
    const result = await this.articleRepository.create(dto)
    await this.articleRepository.save(result)

    return result
  }

  // 列表
  async findAll(queryParams) {
    const { page, limit, title, version, tagId, navId } = queryParams
    const sql = this.articleRepository.createQueryBuilder('article').leftJoinAndSelect('article.tags', 'tags').leftJoinAndSelect('article.category', 'category').orderBy('article.id', 'DESC')

    console.log('queryParams', queryParams)

    title && sql.where('article.title like :title', { title: `%${title}%` })
    navId && sql.andWhere('article.navId = :id', { id: +navId })
    version && sql.andWhere('article.version = :version', { version })
    tagId && sql.andWhere('tags.id = :id', { id: +tagId })

    sql.skip((page - 1) * limit).take(limit)

    return await sql.getManyAndCount()
  }

  // 详情
  async findOne(id) {
    const result = await this.articleRepository.findOne({ where: { id } })
    await this.articleRepository.update(id, { viewsCount: result.viewsCount + 1 })
    return result
  }

  // 修改
  async update(id, dto: UpdateArticleDto) {
    const old = await this.articleRepository.findOne({ where: { id } })
    const vo = await this.articleRepository.merge(old, dto)

    return this.articleRepository.save(vo)
  }

  // 删除
  async remove(id: string) {
    const result = await this.articleRepository.delete(id)
    Logger.log(`删除返回数据：${JSON.stringify(result)}`)

    return result.affected || new HttpException('无法删除，请稍候在试', HttpStatus.BAD_REQUEST)
  }
}
